package com.geely.config;


import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.io.IOException;

/**
 * @author 占助
 * @date 2020/7/14 8:40
 * @description ${消息确认回调函数}
 * @Copyright © 吉利汽车
 * @Version: 1.0
 */
@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate CreateRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory, 才能触发回调函数，无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        //这里是每次都会调用的，不论失败与否
        //ps： 当交换机未找到的时候也会在这里回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("ConfirmCallback:    "+"相关数据："+  correlationData  );
                System.out.println("ConfirmCallback:    "+"确认情况："+  ack  );
                System.out.println("ConfirmCallback:    "+"原因："+  cause  );
            }
        });
        //这里是只有交换机匹配，路由匹配未找到的时候才会调用到 例：/TestMessageAck2
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("ReturnCallback:    "+"消息："+  message  );
                System.out.println("ReturnCallback:    "+"回应码："+  replyCode  );
                System.out.println("ReturnCallback:    "+"回应消息："+  replyText  );
                System.out.println("ReturnCallback:    "+"交换机："+  exchange  );
                System.out.println("ReturnCallback:    "+"路由键："+  routingKey  );
                System.out.println("====================ReturnCallback===========================");
                System.out.println("====================" + new String(message.getBody()) + "===========================");
            }
        });

        return  rabbitTemplate;
    }


}
